<template>
  <div class="">
    <div class="">
      <el-form ref="formRef" :model="form" :rules="rules" :inline="false" label-suffix="：">
        <el-form-item label="账号" prop="userName">
          <el-input v-model="form.userName"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button :loading="signIn.pending.value" type="primary" class="flex-1" @click="onSubmit()">登录</el-button>
          <el-button class="flex-1">注册</el-button>
        </el-form-item>
      </el-form>
      <!-- <div class="">{{ auth.token }}</div> -->
    </div>
  </div>
</template>

<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus';
import { Md5 } from 'ts-md5';
const auth = useAuth();
definePageMeta({
  auth: false,
  layout: 'main',

});


watchEffect(() => {
  if (auth.user) {
    useRouter().replace(
      useRoute().query?.callback ? String(useRoute().query?.callback) : '/',
    );
  }
});


// const auth = ref({ pending: false });

const form = reactive({
  userName: 'admin',
  password: 'admin',
});
const rules = reactive<FormRules>({
  userName: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
});
const formRef = ref<FormInstance>();

const signIn = useAsyncData(
  'signIn',
  async () => {
    if (!formRef.value) return;
    await formRef.value.validate().then(
      async () => {
        let salt = "ueidfisgfilegfiff" + form.userName
        let md5: any = new Md5()
        let password = md5.appendStr(form.password + salt).end().toString()
        const user = await auth.signIn('password', {
          username: form.userName,
          password: password,
        });
        if (user) {
          useRouter().replace(
            useRoute().query?.callback ? String(useRoute().query?.callback) : '/',
          );
        } else {
          ElMessage.error('登录失败,账号密码不正确')
        }

      },
      () => {
        ElMessage.error('请输入账号密码')
        // 表单验证未通过
      },
    );
  },
  {},
);

watchAsyncDataError(signIn);

const onSubmit = async () => {
  signIn.execute();
  const runtimeConfig = useRuntimeConfig();
  runtimeConfig.public.consoeList = []
  // if (!formRef.value) return;
  // await formRef.value.validate().then(
  //   async () => {
  //     const user = await auth.signIn('password', {
  //       userName: form.userName,
  //       password: form.password,
  //     });
  //     console.log('🚀 ~ file: signIn.vue:62 ~ user:', user);
  //     // useRoute().query?.callback
  //     useRouter().replace(
  //       useRoute().query?.callback ? String(useRoute().query?.callback) : '/',
  //     );
  //   },
  //   () => {
  //     // 表单验证未通过
  //   },
  // );
};
</script>
